package cn.wubo.beetsql.controller;

import cn.wubo.beetsql.entity.DemoTable;
import oracle.jdbc.OracleTypes;
import org.beetl.sql.core.OnConnection;
import org.beetl.sql.core.SQLManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

@RestController
@RequestMapping("/beetsql")
public class BeetsqlController {

    @Autowired
    private SQLManager sqlManager;

    @RequestMapping(value = "/testProcedure", method = RequestMethod.GET)
    public List<DemoTable> testProcedure() {

        List<DemoTable> demoTables = sqlManager.executeOnConnection(new OnConnection<List<DemoTable>>(){
            @Override
            public List<DemoTable> call(Connection conn) throws SQLException {
                CallableStatement callableStatement = conn.prepareCall("{ call GETTABLEDATA(?) }");
                callableStatement.registerOutParameter(1, OracleTypes.CURSOR);
                callableStatement.executeQuery();
                ResultSet rs = (ResultSet)callableStatement.getObject(1);
                List<DemoTable> demoTables = sqlManager.getDefaultBeanProcessors().toBeanList(rs,DemoTable.class);
                return demoTables;
            }
        });

        return demoTables;
    }
}
